package cn.eeepay.framework.service.workOrder.impl;

import cn.eeepay.framework.dao.AgentInfoDao;
import cn.eeepay.framework.dao.MerchantInfoDao;
import cn.eeepay.framework.dao.SysDictDao;
import cn.eeepay.framework.dao.workOrder.WorkProductConfigDao;
import cn.eeepay.framework.dao.workOrder.WorkTypeDao;
import cn.eeepay.framework.dao.workOrder.WorkWarningRecordDao;
import cn.eeepay.framework.model.AgentInfo;
import cn.eeepay.framework.model.MerchantInfo;
import cn.eeepay.framework.model.UserLoginInfo;
import cn.eeepay.framework.model.workOrder.WarningConfig;
import cn.eeepay.framework.model.workOrder.WorkOrder;
import cn.eeepay.framework.model.workOrder.WorkProductConfigEntity;
import cn.eeepay.framework.model.workOrder.WorkWarningRecordEntity;
import cn.eeepay.framework.service.workOrder.WorkOrderService;
import cn.eeepay.framework.service.workOrder.WorkProductConfigService;
import cn.eeepay.framework.util.*;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.task.TaskExecutor;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.net.URLEncoder;
import java.util.*;


@Service("workProductConfigService")
public class WorkProductConfigServiceImpl implements WorkProductConfigService {

    private Logger log = LoggerFactory.getLogger(WorkProductConfigServiceImpl.class);


    @Resource
    private WorkProductConfigDao workProductConfigDao;

    @Resource
    private WorkTypeDao workTypeDao;

    @Resource
    private TaskExecutor taskExecutor;

    @Resource
    private AgentInfoDao agentInfoDao;

    @Resource
    private WorkOrderService workOrderService;

    @Resource
    private WorkWarningRecordDao workWarningRecordDao;

    @Resource
    private MerchantInfoDao merchantInfoDao;

    @Resource
    private SysDictDao sysDictDao;

    @Override
    public WorkProductConfigEntity getById(Long id) {
        return workProductConfigDao.getById(id);
    }

    @Override
    public boolean checkOrderType(String workTypeId) {
        return workProductConfigDao.checkOrderType(workTypeId) > 0;
    }

    @Override
    public WorkProductConfigEntity getDefaultconfig() {
        WorkProductConfigEntity info = workProductConfigDao.getDefaultconfig();
        if (info != null) {
            //回显 首刷投诉字段配置 工单类型
            if (StringUtil.isNotBlank(info.getWorkTypeList())) {
                String[] workTypeArr = info.getWorkTypeList().split(",");
                List<String> ids = Arrays.asList(workTypeArr);
                if (ids != null && ids.size() > 0) {
                    info.setWorkTypes(workTypeDao.getBatchWorkTypes(Arrays.asList(workTypeArr)));
                }
            }
        }


        return info;
    }


    @Override
    public ResultModel updateById(WorkProductConfigEntity workProductConfig) {
        workProductConfig.setOperator(getLoginUser().getUsername());
        int update = workProductConfigDao.updateById(workProductConfig);
        if (update == 1) {
            return ResultModel.ok("修改成功");
        } else {
            return ResultModel.ok("修改失败");
        }
    }

    @Override
    public ResultModel removeByIds(List<Long> asList) {
        return null;
    }

    private UserLoginInfo getLoginUser() {
        return (UserLoginInfo) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    }

    @Override
    public void toWarning(final WorkOrder order, final UserLoginInfo userLoginInfo) {
        taskExecutor.execute(new Runnable() {
            @Override
            public void run() {
                log.info("异步生成预警开始===============");

                if (StringUtil.isBlank(order.getMerchantNo())) {
                    return;
                }

                if (StringUtil.isBlank(order.getWorkProductType()) || !order.getWorkProductType().equals("1")) {
                    return;
                }
                //预警配置是否存在
                WorkProductConfigEntity defaultconfig = workProductConfigDao.getDefaultconfig();
                if (defaultconfig == null) {
                    return;
                }
                //是否开启
                if (defaultconfig.getWarningSwitch() == null || defaultconfig.getWarningSwitch() != 1) {
                    return;
                }
                //配置是否存在
                if (StringUtil.isBlank(defaultconfig.getWarningConfig())) {
                    return;
                }
                MerchantInfo merchantInfo = merchantInfoDao.selectByMerNo(order.getMerchantNo());
                if (merchantInfo == null) {
                    return;
                }
                AgentInfo agentInfo = agentInfoDao.select(merchantInfo.getAgentNo());
                if (agentInfo == null) {
                    return;
                }

                //具体配置
                WarningConfig warningConfig = JSON.parseObject(defaultconfig.getWarningConfig(), WarningConfig.class);
                if (warningConfig == null) {
                    return;
                }
                Date begin = DateUtils.getTimesMonthmorning();
                Date end = new Date();
                //一级代理商预警
                if (1 == agentInfo.getAgentLevel()) {
                    if (warningConfig.getOneLevelAgent() == null
                            || StringUtil.isBlank(warningConfig.getOneLevelAgent().getWarningContent())
                            || StringUtil.isBlank(warningConfig.getOneLevelAgent().getWarningNumber())
                            || StringUtil.isBlank(warningConfig.getOneLevelAgent().getWarningTitle())) {
                        return;
                    }
                    int warningNum = Integer.parseInt(warningConfig.getOneLevelAgent().getWarningNumber());
                    if (warningNum <= 0) {
                        return;
                    }
                    //获取已经存在的预警工单
                    int count = workOrderService.countOrdersOneAgent("1", agentInfo.getAgentNo(), begin, end);
                    if (count > 0 && count % warningNum == 0) {
                        log.info("开始生成一级代理预警");
                        WorkWarningRecordEntity info = new WorkWarningRecordEntity();
                        info.setWorkProductType("1");
                        info.setAgentNo(agentInfo.getAgentNo());
                        info.setWarningNumber(count);
                        info.setWarningTitle(warningConfig.getOneLevelAgent().getWarningTitle());
                        info.setWarningContent(warningConfig.getOneLevelAgent().getWarningContent());
                        info.setWarningNumberConfig(warningNum);
                        info.setPopStatus(0);
                        info.setOperator(userLoginInfo.getUsername());
                        workWarningRecordDao.save(info);
                        log.info("生成一级代理预警成功");
                        toPush(warningConfig.getOneLevelAgent().getWarningTitle(),warningConfig.getOneLevelAgent().getWarningContent(),agentInfo.getAgentNo());
                    }

                } else {
                    //还要生成所属预警
                    if (warningConfig.getAgent() != null
                            && StringUtil.isNotBlank(warningConfig.getAgent().getWarningContent())
                            && StringUtil.isNotBlank(warningConfig.getAgent().getWarningNumber())
                            && StringUtil.isNotBlank(warningConfig.getAgent().getWarningTitle())) {
                        int warningNum = Integer.parseInt(warningConfig.getAgent().getWarningNumber());
                        if (warningNum <= 0) {
                            return;
                        }
                        //获取已经存在的预警工单
                        int count = workOrderService.countOrdersBelongAgent("1", agentInfo.getAgentNo(), begin, end);
                        if (count > 0 && count % warningNum == 0) {
                            log.info("开始生成直属代理预警");
                            WorkWarningRecordEntity info = new WorkWarningRecordEntity();
                            info.setWorkProductType("1");
                            info.setAgentNo(agentInfo.getAgentNo());
                            info.setWarningNumber(count);
                            info.setWarningTitle(warningConfig.getAgent().getWarningTitle());
                            info.setWarningContent(warningConfig.getAgent().getWarningContent());
                            info.setWarningNumberConfig(warningNum);
                            info.setPopStatus(0);
                            info.setOperator(userLoginInfo.getUsername());
                            workWarningRecordDao.save(info);
                            log.info("生成直属代理预警成功");
                            toPush(warningConfig.getAgent().getWarningTitle(),warningConfig.getAgent().getWarningContent(),agentInfo.getAgentNo());
                        }
                    }

                    //非一级代理商 需要生成一级预警
                    if (warningConfig.getOneLevelAgent() != null
                            && StringUtil.isNotBlank(warningConfig.getOneLevelAgent().getWarningContent())
                            && StringUtil.isNotBlank(warningConfig.getOneLevelAgent().getWarningNumber())
                            && StringUtil.isNotBlank(warningConfig.getOneLevelAgent().getWarningTitle())) {
                        int warningNum = Integer.parseInt(warningConfig.getOneLevelAgent().getWarningNumber());
                        if (warningNum <= 0) {
                            return;
                        }
                        //获取已经存在的预警工单
                        AgentInfo oneAgentInfo = agentInfoDao.select(agentInfo.getOneLevelId());
                        if (oneAgentInfo == null) {
                            return;
                        }
                        int count = workOrderService.countOrdersOneAgent("1", oneAgentInfo.getAgentNo(), begin, end);
                        if (count > 0 && count % warningNum == 0) {
                            log.info("开始生成一级代理预警");
                            WorkWarningRecordEntity info = new WorkWarningRecordEntity();
                            info.setWorkProductType("1");
                            info.setAgentNo(oneAgentInfo.getAgentNo());
                            info.setWarningNumber(count);
                            info.setWarningTitle(warningConfig.getOneLevelAgent().getWarningTitle());
                            info.setWarningContent(warningConfig.getOneLevelAgent().getWarningContent());
                            info.setWarningNumberConfig(warningNum);
                            info.setPopStatus(0);
                            info.setOperator(userLoginInfo.getUsername());
                            workWarningRecordDao.save(info);
                            log.info("生成一级代理预警成功");
                            toPush(warningConfig.getOneLevelAgent().getWarningTitle(),warningConfig.getOneLevelAgent().getWarningContent(),oneAgentInfo.getAgentNo());
                        }
                    }
                }
                log.info("异步生成预警结束===============");
            }
        });

    }

    private void toPush(String title,String content,String merchantNo) {
        final String Token = "a185faf4c55807bca4bcfdaae06b58fa";
        final String USER_INFO_ID = "4IE5DhZE4IJ2gdv9YmDr6jfaaIBBlyafFNPz2wYXtqN";
        final String PATH = "/riskhandle/commonJPush";
        try {
            String authCode = Md5.md5Str(USER_INFO_ID + merchantNo + Token).toUpperCase();
            String paramStr = "title="+title+"&token=" + Token + "&merchantNo=" + merchantNo + "&authCode=" + authCode + "&content=" + URLEncoder.encode(content, "UTF-8");
            String url = sysDictDao.getByKey("CORE_URL").getSysValue() + PATH;
            log.info("极光推送参数：",paramStr);
            String str = HttpUtils.sendPost(url, paramStr, "UTF-8");
            log.info("极光推送结果：" + str);
        }catch (Exception e){
            log.error("极光推送失败");
            e.printStackTrace();
        }

    }
}